<template>
    <!-- <h3>搜索页</h3> -->
    <div class="search">
        <div class="container">
            <button class="btn btn-sm btn-danger" @click="goBack"> <i class="bi bi-arrow-left"></i> 返回</button>
        </div>
        <div class="container">
            <input @keydown.enter="articleSearchFn" v-model="text" class="input" type="text" placeholder="请输入关键字">
        </div>

        <div class="container" v-if="historys.length != 0">
            <div class="history">
                <span>历史搜索:</span>
                <span v-for="(kw,index) in historys" class="text">
                     <i style="font-style: normal; cursor: pointer;" @click="chooseHistoryKeyword(kw)">{{ kw }}</i>
                    <sup style="font-size: 20px; cursor: pointer;" @click="removeKeyword(index)">x</sup>
                </span>
            </div>
        </div>

        <div class="container">
            <ListItem :arr="articles" v-if="articles.length !=0" />
            <p v-else class="message">暂无搜索内容~~</p>
        </div>

    </div>
</template>
<style lang="less">
.search {
    padding: 15px 0px;
    .container {
        padding-top: 10px;
        padding-bottom: 10px;

        .input {
            width: 100%;
            height: 50px;
            border-radius: 25px;
            outline: none;
            border: 1px solid #ccc;
            padding-left: 30px;
        }
    }

    .history {
        .text {
            color: #666;
            display: inline-block;
            vertical-align: middle;
            border: 1px solid #f0f0f0 ; 
            padding: 10px 10px 6px 10px;
            font-size: 14px;
            margin: 5px ;
            border-radius: 4px;
        }
    }

    .message {
        padding: 50px 0px;
        text-align: center;
        color: #ccc;
        font-size: 20px;
        font-weight: bold;
    }
}
</style>

<script setup lang="ts">
import ListItem from '@/components/ListItem.vue'
import { useRouter } from 'vue-router'
import { articleSearch, host } from '@/api/index'
import { ref } from 'vue'

const router = useRouter()

const goBack = () => {
    router.go(-1)
}
interface IItem {
    [key:string]: string | any
}

const historys = ref<string []>([])

// 本地存储
let historyStr = localStorage.getItem("HISTORY")
if(historyStr) {
    historys.value = JSON.parse(historyStr)
}

const text = ref<string>("")

const articles = ref<any[]>([])

// 按回车执行搜索方法
const articleSearchFn = async () => {
    if (text.value == "") {
        alert("输入框不能为空");
        return false;
    }
    if(historys.value.indexOf(text.value) >-1){
        // 先删除旧记录 
        let oldIndex = historys.value.indexOf(text.value)
        historys.value.splice(oldIndex,1)
        // 再添加新记录
        historys.value.push(text.value)// 添加历史记录
    }
    else {
        historys.value.push(text.value)// 添加历史记录
    }

    localStorage.setItem("HISTORY",JSON.stringify(historys.value))//缓存数据在本地

    // 先清空数组
    articles.value = []

    await articleSearch({ keyword: text.value })
        .then(
            (resData: any) => {
                console.log(1,resData)
                let { result } = resData
                let arr = result.map((item: IItem) => {
                    const date = new Date(item.createAt)
                    item.createAt = date.toLocaleDateString() + " " + (date.toLocaleTimeString())
                    item.src = host + item.src;
                    return item;
                })
                // 然后 再赋值 （vue就能检测数据变化，从而更新视图）
                articles.value =arr;
            }
        )
}

// 点击删除关键字
const removeKeyword = (index:number) => {
    historys.value.splice(index,1)
}

// 点击历史记录关键字
const chooseHistoryKeyword = async (txt:string) =>{
    text.value = txt;
    articles.value = [];//先清空再赋值
    await articleSearch({ keyword: txt })
        .then(
            (resData: any) => {
                console.log(2,resData)
                let { result } = resData
                let arr = result.map((item: IItem) => {
                    const date = new Date(item.createAt)
                    item.createAt = date.toLocaleDateString() + " " + (date.toLocaleTimeString())
                    item.src = host + item.src;
                    return item;
                })
                articles.value =arr;
            }
        )
}
</script>
